package com.gecolin.geekweek1.loader;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;

public class GeColinClassLoader extends ClassLoader {
    public static void main(String[] args) throws Exception{
        final String className = "Hello";
        ClassLoader classLoader = new GeColinClassLoader();
        Class<?> clazz = classLoader.loadClass(className);
        for(Method m:clazz.getDeclaredMethods()){
            System.out.println(clazz.getSimpleName()+"."+m.getName());
            Object instace = clazz.getDeclaredConstructor().newInstance();
            Method method = clazz.getMethod(m.getName());
            method.invoke(instace);
        }

    }
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException{
        String resourcePath = name.replace(".","/");
        final String suffix = ".xlass";
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(resourcePath+suffix);
        try{
            //读取数据
            int length = inputStream.available();
            byte[] byteArray = new byte[length];
            inputStream.read(byteArray);
            //转换
            byte[] classBytes = decode(byteArray);
            return defineClass(name,classBytes,0,classBytes.length);
        }catch(IOException e){
            throw new ClassNotFoundException(name,e);
        }finally {
            try{
                inputStream.close();
            }catch(IOException e){
                e.printStackTrace();
            }

        }
    }
    //解码
    private static byte[] decode(byte[] byteArray){
        byte[] targetArray = new byte[byteArray.length];
        for(int i = 0;i<byteArray.length;i++){
            targetArray[i] = (byte)(255-byteArray[i]);
        }
        return targetArray;
    }
}
